import { handleActions } from 'redux-actions'
import { addProductToLocalCart, changeProductNumber, deleteProductFromLocalCart, saveCarts } from '../actions/cart.actions'

const initialState = []
function handleAddProductToLocalCart(state, action) {
  const products = JSON.parse(JSON.stringify(state))
  const product = products.find(item => item.id === action.payload.id)
  if(product) {
    // 商品存在购物车中
    product.count++
  }else {
    // 商品不存在购物车中
    products.push(action.payload)
  }
  return products
}

// 向本地store保存购物车数据列表
const handleSaveCarts = (state, action) => action.payload

// 删除本地store购物车中的商品
const handleDeleteProductFromLocalCart = (state, action) => {
  const newState = JSON.parse(JSON.stringify(state))
  newState.splice(action.payload, 1)
  return newState
}

// 修改本地购物车商品数量
const handleChangeProductNumber = (state, action) => {
  const newState = JSON.parse(JSON.stringify(state))
  const product = newState.find(item => item.id === action.payload.id)
  product.count = action.payload.count
  return newState
}
const cartReducer =  handleActions({
  // 将商品添加到本地的购物车数据中
  [addProductToLocalCart]: handleAddProductToLocalCart,
  [saveCarts]: handleSaveCarts,
  [deleteProductFromLocalCart]: handleDeleteProductFromLocalCart,
  [changeProductNumber]: handleChangeProductNumber
}, initialState)

export default cartReducer